import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
import java.io.*;

/** AppletServlet shows

   -- How to send parameters to servlet through GET method and get
      data from servlet.
	Read binary from servlet doesn't work. I have tried read
	bytes, read object. Nothing works so far.
   -- How to send parameters to servlet through POST method and get
      data from servlet. Not done yet, the following steps can be used
      to pass parameter with POST method:
	URLConnection conn;
	URL           url;
	PrintStream   out;
	url = new URL("http://www.cs.csubak.edu/servlets/ServletApplet");
	conn = url.openConnection();
	conn.setDoOutput(true);
	conn.setDoInput(true);
	out = new PrintStream( conn.getOutputStream() );
	// make message as string with format:  pars = key=value&key=value ...
	out.print( URLEncoder.encode( parts ) );
	out.flush();
	out.close();

     To read data, use the same method as GET method, and try the output from server
     as text.
	
*/

public class AppletServlet extends Applet implements ActionListener {

  Label lbDateNumber = new Label("Press a button to get data from servlet");
  Button btnNumber = new Button("Number");
  Button btnDate = new Button("Date");
  public void init() {
	setLayout( new GridLayout(1, 3) );
	lbDateNumber.setFont(new Font("Numbers-Roman", Font.BOLD, 16));
	btnNumber.addActionListener(this);
	btnDate.addActionListener(this);
	add(lbDateNumber);
	add(btnNumber);
	add(btnDate);
  }

  public void actionPerformed (ActionEvent evt) {
	if ( evt.getSource() instanceof Button ) {
		Button btn = (Button) evt.getSource();
		String lb = btn.getLabel();
		if ( lb.equals("Date") || lb.equals("Number") )
			lbDateNumber.setText(getStringFromServletWithGetMethod(lb));
		// else    ;
	}
  }

  String getStringFromServletWithGetMethod ( String par ) {
    try {
	InputStream in;
	URL url;
	url = new URL("http://www.cs.csubak.edu/servlets/ServletApplet"+"?type="+par);
	in = url.openStream();
	byte bytes[] = new byte[101];
	int i = in.read(bytes);
	if ( par.equals("Date") ) return new String(bytes, 0, i);
	else {    // read binary data: Cannot get it to work.
		// Integer n = new Integer(0);
		// ObjectInputStream oin = new ObjectInputStream(in);
		// n = (Integer) oin.readObject();
		i = in.read(bytes);
		return "integer generated "+  i + ": " + new String(bytes);
	}
		
    } catch (Exception e) { e.printStackTrace(); }
    return "";
  } 
}
